﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;


using System.Windows.Forms;

public class FileType
{

    public void test()
    {
        string filePath = @"C:\\Users\\QH\\Desktop\\部编版7-9年级初中语文上下册\\统编版语文八年级上册.pdf";
        string str;
        str = System.IO.Path.GetFullPath(filePath);          //"获取文件的全路径：" + 
        str =  System.IO.Path.GetDirectoryName(filePath);          //"获取文件所在的目录：" +
        str = System.IO.Path.GetFileName(filePath);          //"获取文件的名称含有后缀：" + 
        str = System.IO.Path.GetFileNameWithoutExtension(filePath);          //"获取文件的名称没有后缀：" + 
        str = System.IO.Path.GetExtension(filePath);          //"获取路径的后缀扩展名称：" + 
        str = System.IO.Path.GetPathRoot(filePath);          //"获取路径的根目录：" + 
    }

    public static string GetAppPoint()  //APP所在位置
    {
        return System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取应用程序基目录的名称
    }
    public static string GetDeskPoint()  //获取桌面位置
    {
        return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    }
    public static Boolean Existence(string path)  //判断文件或文件夹是否存在
    {
        return System.IO.File.Exists(path);
    }
    public static List<string> PathGetFileType(string path, string type)  //查找路径下指定的文件类型
    {
        return new List<string>(Directory.GetFiles(path, "*" + type));
    }
    public static FileInfo[] PathGetFileInfo(string path, string type)  //获取指定文件指定文件类型的信息
    {
        List<string> ListStringPath = PathGetFileType(path, type);
        FileInfo[] fileInfo = new FileInfo[0];
        if (ListStringPath.Count != 0)
        {
            fileInfo = new FileInfo[ListStringPath.Count];
            for (int i = 0; i < ListStringPath.Count; i++)
            {
                fileInfo[i] = new FileInfo(ListStringPath[i]);
            }
        }
        return fileInfo;
    }
    public static FileInfo[] PathGetFileInfo(string path)  //获取指定文件的信息
    {
        DirectoryInfo root = new DirectoryInfo(path);
        FileInfo[] files = root.GetFiles();
        SortAsFileCreationTimeAsc(ref files);
        return files;
    }

    //-----------------基本文件操作，读写，合并----------------------------------------------------------------------------------------/

    static public List<string> ReadLine(string path)  //读取文本，一行一行的读
    {
        List<string> list = new List<string>();
        StreamReader HexReader = new StreamReader("C:\\Users\\QH\\Desktop\\关于数据部分.txt");
        //File.WriteAllText(path, s); // 将文本内容写入文件
        while (true)
        {
            string szLine = HexReader.ReadLine(); //读取一行数据
            if (szLine == null) //读完所有行
            {
                break;
            }
            list.Add(szLine);
        }
        return list;
    }



    static public Byte[] Read(string path)  //读文件
    {
        if (!File.Exists(path))
        {
            return new byte[0];
        }
        FileStream fs = new FileStream(path, FileMode.Open);
        Byte[] buf = new byte[fs.Length];
        fs.Seek(0, SeekOrigin.Begin);    // 定位到第0个字节
        fs.Read(buf, 0, buf.Length);//将文件读到byte数组中
        fs.Close();
        return buf;
    }

    static public string GetFileName()   //获取保存文件的路径和文件名
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            return saveFileDialog.FileName;
        }
        return "";
    }
    static public string GetFilePath(string type)   //打开指定的路径下指定后缀的文件
    {
        OpenFileDialog file = new OpenFileDialog();

        file.RestoreDirectory = true;//记忆上次打开的目录

        file.Filter = "二进制文件(*" + type + ")|*" + type;//文件过滤器
        file.Multiselect = false;//设置是否允许多选
        if (file.ShowDialog() == DialogResult.OK)
        {
            return file.FileName;
        }
        return "";
    }
    static public string[] GetFilesPath(string type)   //打开多少指定的路径下指定后缀的文件
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "文件(*" + type + ")|*" + type;
        openFileDialog.Multiselect = true;//允许多选
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            return openFileDialog.FileNames;
        }
        string[] strings = new string[0]; 
        return strings;
    }

    static public string MakeTimeFilePathName(string path, string suffixName,string type)  //制做一个以当前时间的文件名字路径
    {
        System.DateTime dte = System.DateTime.Now;
        string timeString = dte.GetDateTimeFormats('s')[0].ToString();     //2005-11 -05T14:06:25
        //return path + "//" + suffixName + "(" + System.Text.RegularExpressions.Regex.Replace(timeString, @"[^0-9]+", "") + ")" + type;
        return path + "//" + suffixName + "(" + timeString.Replace("-",".").Replace(":",".") + ")" + type;
    }
    static public void SaveFile(string path, Byte[] data)   //保存文件
    {
        FileStream ws = new FileStream(path, FileMode.Create);
        ws.Write(data, 0, data.Length);  //将byte数组写入文件中
        ws.Flush();
        ws.Close();
    }

    //-----------------文件排序----------------------------------------------------------------------------------------/
    public static void SortAsFileNameAsc(ref FileInfo[] arrFi)//C#按文件名排序（顺序）
    {
        Array.Sort(arrFi, delegate (FileInfo x, FileInfo y) { return x.Name.CompareTo(y.Name); });
    }
    public static void SortAsFileNameDesc(ref FileInfo[] arrFi)//C#按文件名排序（倒序）
    {
        Array.Sort(arrFi, delegate (FileInfo x, FileInfo y) { return y.Name.CompareTo(x.Name); });
    }
    public static void SortAsFileCreationTimeAsc(ref FileInfo[] arrFi)// C#按创建时间排序（顺序）
    {
        Array.Sort(arrFi, delegate (FileInfo x, FileInfo y) { return x.CreationTime.CompareTo(y.CreationTime); });
    }
    public static void SortAsFileCreationTimeDesc(ref FileInfo[] arrFi)// C#按创建时间排序（倒序）
    {
        Array.Sort(arrFi, delegate (FileInfo x, FileInfo y) { return y.CreationTime.CompareTo(x.CreationTime); });
    }

    //-----------------两个文件比较----------------------------------------------------------------------------------------/

    public Boolean CompareByMD5(string file1, string file2)  //对比两个文件是否相等方法1
    {
        // 使用.NET内置的MD5库
        using (var md5 = MD5.Create())
        {
            byte[] one, two;
            using (var fs1 = File.Open(file1, FileMode.Open))
            {
                one = md5.ComputeHash(fs1); // 以FileStream读取文件内容,计算HASH值
            }
            using (var fs2 = File.Open(file2, FileMode.Open))
            {
                two = md5.ComputeHash(fs2);// 以FileStream读取文件内容,计算HASH值
            }
           
            return BitConverter.ToString(one) == BitConverter.ToString(two); // 将MD5结果(字节数组)转换成字符串进行比较
        }
    }
    private static bool CompareByReadOnlySpan(string file1, string file2)  //对比两个文件是否相等方法2
    {
        const int BYTES_TO_READ = 1024 * 10;

        //using (FileStream fs1 = File.Open(file1, FileMode.Open))
        //using (FileStream fs2 = File.Open(file2, FileMode.Open))
        //{
        //    byte[] one = new byte[BYTES_TO_READ];
        //    byte[] two = new byte[BYTES_TO_READ];
        //    while (true)
        //    {
        //        int len1 = fs1.Read(one, 0, BYTES_TO_READ);
        //        int len2 = fs2.Read(two, 0, BYTES_TO_READ);
        //        // 字节数组可直接转换为ReadOnlySpan
        //        if (!((ReadOnlySpan<byte>)one).SequenceEqual((ReadOnlySpan<byte>)two)) return false;
        //        if (len1 == 0 || len2 == 0) break;  // 两个文件都读取到了末尾,退出while循环
        //    }
        //}
        return true;
    }


    //-----------------加密解密文件----------------------------------------------------------------------------------------/
    public static Byte[] EncryptionPassWord = new byte[16] { 0X15, 0X12, 0Xa3, 0X14, 0Xd5, 0X16, 0X17, 0X18, 0X19, 0X10, 0X11, 0X52, 0Xe3, 0Xf4, 0X95, 0Xb7, };
    static public Byte[] ReadEncryptionFile(string path)  //读取AES128加密文件
    {
        Byte[] data = DataOperation.Aes128EncryptionAndDecryption(FileType.Read(path), EncryptionPassWord, false);
        if (Modebus.CheckCRC16(data) == true)
        {
            return DataOperation.DataIntercept(data, 0, (Int32)(data.Length - 2));
        }
        else
        {
            return new byte[0];
        }
    }
    static public void SaveEncryptionFile(string path, Byte[] bytes) //写入AES128加密文件
    {
        Byte[] data = new byte[bytes.Length + 2];
        Buffer.BlockCopy(bytes, 0, data, 0, bytes.Length);
        Modebus.Crc16DataType crc16 = Modebus.CRC16Calculation(DataOperation.DataIntercept(data, 0, (Int32)(data.Length - 2)));
        data[data.Length - 2] = crc16.H;
        data[data.Length - 1] = crc16.L;
        FileType.SaveFile(path, DataOperation.Aes128EncryptionAndDecryption(data, EncryptionPassWord, true));
    }


    //-----------------文件格式转换----------------------------------------------------------------------------------------/
    static public Byte[] HexToBinFile(string inPath)  //HEX转BIN,注意些处要的是路径
    {
        StringBuilder sb = new StringBuilder();
        StreamReader HexReader = new StreamReader(inPath);
        while (true)
        {
            string szLine = HexReader.ReadLine(); //读取一行数据
            if (szLine == null) //读完所有行
            {
                break;
            }
            if (szLine.Substring(0, 1) == ":") //判断第1字符是否是:
            {
                if (szLine.Substring(1, 8) == "00000001")//数据结束
                {
                    break;
                }
                if ((szLine.Substring(1, 1) == "1") || (szLine.Substring(3, 4) != "0000" && szLine.Substring(1, 1) == "0"))
                {
                    sb.Append(szLine.Substring(9, szLine.Length - 11));//读取有效字符：后0和1
                }
            }





        }
        string hexString = sb.ToString();
        byte[] binBuffer = new byte[hexString.Length / 2];
        for (int i = 0; i < hexString.Length / 2; i++) //两字符合并成一个16进制字节
        {
            binBuffer[i] = (byte)Int16.Parse(hexString.Substring(2 * i, 2), NumberStyles.HexNumber);
        }
        return binBuffer;
    }

}





